package com.nbicc.core.common;

import com.github.pagehelper.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lilingyan
 */
public class ResponseUtil {

    public static ResponseEntity<ModelMap> ok() {
        return setModelMap(HttpStatus.OK, null , null);
    }

    public static ResponseEntity<ModelMap> ok(Object data) {
        return setModelMap(HttpStatus.OK, data , null);
    }

    public static ResponseEntity<ModelMap> ok(Object data , Object message) {
        return setModelMap(HttpStatus.OK, data , message);
    }

    public static ResponseEntity<ModelMap> setModelMap(HttpStatus status, Object data , Object message) {
        ModelMap modelMap = new ModelMap();
        if (data != null) {
            if (data instanceof Page) {
                Page<?> page = (Page<?>) data;
                Map<String, Object> map = new HashMap<>();
                map.put("total", page.getTotal());
                map.put("records", page.getResult());
                modelMap.put("data", map);
            } else {
                modelMap.put("data", data);
            }
        }
        modelMap.put("status", status.value());
        modelMap.put("message", message);
        modelMap.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.status(status).body(modelMap);
    }

}
